package com.tenqian.crm.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.tenqian.AlipayConfig;
import com.tenqian.Result;
import com.tenqian.crm.domain.TqUser;
import com.tenqian.crm.repository.OrderRepository;
import com.tenqian.crm.service.OrderService;
import com.tenqian.crm.service.TqUserService;
import com.tenqian.enums.ResultEnum;
import com.tenqian.order.domain.Order;
import com.tenqian.order.domain.Vip;
import com.tenqian.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    TqUserService tqUserService;
    @Autowired
    OrderRepository orderRepository;

    @Override
    public Result getSign(String productCode, String token) {
        TqUser userByToken = tqUserService.findUserByToken(token);
        //创建订单
        Vip[] values = Vip.values();
        Order order = null;
        for (Vip value : values) {
            if (value.getCode().equals(productCode)) {
                order = new Order();
                order.setDuration(value.getDuration());
                order.setOrderDate(new Date());
                order.setUserId(userByToken.getId());
                order.setProductName(value.getName());
                order.setPrice(value.getPrice());
                orderRepository.save(order);
                break;
            }
        }
        //没有找到对应的vip套餐
        if (order == null) return ResultUtil.error(ResultEnum.UNKNOWN_PRODUCT_CODE);
        //已生成订单得到支付宝sign
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("sign", getAliSign(order));
        resultMap.put("orderId", order.getId());
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result delOrder(String id) {
        orderRepository.delete(id);
        return ResultUtil.success();
    }

    @Override
    public Order findOrderById(String id) {
        return orderRepository.findOne(id);
    }

    private String getAliSign(Order order) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
//        model.setBody("我是测试数据");
        model.setSubject(order.getProductName());
        model.setOutTradeNo(order.getId());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(order.getPrice());
        model.setProductCode(AlipayConfig.PRODUCTCODE);//固定值
        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notify_url);
        request.setReturnUrl(AlipayConfig.return_url);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody();//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Order> findAll() {
        return null;
    }

    @Override
    public Page pageData(Specification<Order> specification, Pageable pageable) {
        return null;
    }

    @Override
    public void save(Iterable<Order> iterable) {

    }

    @Override
    public Result save(Order order) {
        return ResultUtil.success(orderRepository.save(order));
    }
}
